package cn.jji8.createX.slowPlaceBlock;

import cn.jji8.createX.Main;
import net.md_5.bungee.api.ChatMessageType;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitTask;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SuppressWarnings("unused")
public class SlowPlaceBlockManger implements Runnable{
    static final SlowPlaceBlockManger slowPlaceBlock = new SlowPlaceBlockManger();
    static final List<CanPlaceBlock> soonPlaceBlockList = new ArrayList<>();
    static BukkitTask bukkitTask = null;
    //即将发给玩家的消息
    static Map<Player,String> sendMessageMap = new HashMap<>();

    //玩家填充数度
    public static int PlayerSpeed = 1;

    //全服最大填充速度
    public static int AllPlayerSpeed = 100;

    @Override
    public void run() {
        long time = System.currentTimeMillis();
        if(soonPlaceBlockList.isEmpty()){
            bukkitTask.cancel();
            return;
        }
        no1:for(int xianziAll = 0,xianzi=0;xianzi<PlayerSpeed;xianzi++){

            for(int i=0;i<soonPlaceBlockList.size();i++){
                //没次填充时间不能超过40毫秒
                if(System.currentTimeMillis()-time>20){
                    break no1;
                }
                //限制全部的soonPlaceBlockList只调用100次
                if(xianziAll>AllPlayerSpeed){
                    break no1;
                }else {
                    xianziAll++;
                }

                CanPlaceBlock canPlaceBlock = soonPlaceBlockList.get(i);
                canPlaceBlock = canPlaceBlock.place();
                if(canPlaceBlock!=null){
                    soonPlaceBlockList.set(i,canPlaceBlock);
                }else{
                    //noinspection SuspiciousListRemoveInLoop
                    soonPlaceBlockList.remove(i);
                }
            }
        }
        for(Player player:sendMessageMap.keySet()){
            player.spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText(sendMessageMap.get(player)));
        }
        sendMessageMap.clear();
    }
    public static void sendMessage(Player player,String s){
        sendMessageMap.put(player,s);
    }
    /**
     * 添加一个待填充方块
     * */
    public static void addSoonPlaceBlock(CanPlaceBlock soonPlaceBlock){
        soonPlaceBlockList.add(soonPlaceBlock);
        if(bukkitTask==null){
            bukkitTask = Bukkit.getScheduler().runTaskTimer(Main.getMain(),slowPlaceBlock,1,1);
        }
        if(bukkitTask.isCancelled()){
            bukkitTask = Bukkit.getScheduler().runTaskTimer(Main.getMain(),slowPlaceBlock,1,1);
        }
    }
}
